//
//  WBNetworkManager.swift
//  weiboswift
//
//  Created by dingzhibing on 2017/3/18.
//  Copyright © 2017年 dingzhibing. All rights reserved.
//

import UIKit
import AFNetworking

//swift 枚举支持任意数据类型
enum WBHTTPMethod{
    case GET
    case POST
}

//网络管理工具
final class WBNetworkManager: AFHTTPSessionManager {
    
    //静态区／常量
    static let shared:WBNetworkManager = {
        //实例化对象
        let instance = WBNetworkManager()
        
        //设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    lazy var userAccount = WBUserAccount()
    //用户登录标记 【计算型属性】
    var userLogon:Bool {
        return userAccount.access_token != nil
    }

    /// 专门负责拼接 token 网络请求方法
    func tokenRequest(method:WBHTTPMethod = .GET, URLString:String, parameters:[String:AnyObject]?, completion: @escaping (_ json:Any?,_ isSuccess:Bool)->()){
        
        guard let token = userAccount.access_token else {
            //发送通知 登录
            print("没有token，请登录")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue:WBUserShouldLoginNotification), object: nil)
            completion(nil, false)
            return
        }
        
        var parameters = parameters
        
        
        //添加token
        if parameters == nil {
            parameters = [String:AnyObject]()
        }
        
        parameters!["access_token"] = token as AnyObject
        
        //调用 request 发起真正的网络请求方法
        request(method: method,URLString: URLString, parameters: parameters, completion: completion)
    }
    
    //使用一个函数封装AFN的GET／POST请求
    //option+command+/ 快速注释
    /// 封装AFN的get／post
    ///
    /// - Parameters:
    ///   - method: GET/POST
    ///   - URLString: URLString
    ///   - parameters: 参数字典
    ///   - completion:
    func request(method:WBHTTPMethod = .GET, URLString:String, parameters:[String:AnyObject]?, completion: @escaping (_ json:Any?,_ isSuccess:Bool)->()) {
        
        let success = { (task:URLSessionDataTask,json:Any?)->() in
            completion(json,true)
        }
        
        
        let failure = { (task:URLSessionDataTask?, error:Error) in
            print("网络请求错误：\(error)")
            
            //针对403 处理token
            if (task?.response as? HTTPURLResponse)?.statusCode == 403{
                print("token 过期了")
                
                //FIXME: 发送通知（方法不知道被谁调用 谁接收到通知，谁处理）
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: "bad token")
            }
            
            completion(nil,false)
        }
        
        if method == .GET{
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
        
        
    }
}
